/*
 * @Author: silence
 * @Date: 2023-07-05 11:28:24
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-15 11:41:19
 * @Description: 电站设置-中间（电价、货币类型）
 */
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_base_widget_package/tools/SilUtilsTools.dart';

import '../../../common/widgets/cubitWidget/BottomSheetView.dart';
import '../../../utils/color/ColorUtils.dart';
import '../Controller/PowerStationController.dart';
import 'PowerStationSetItem.dart';

class PsSetCenterView extends StatefulWidget {
  const PsSetCenterView({super.key});

  @override
  State<PsSetCenterView> createState() => _PsSetCenterViewState();
}

class _PsSetCenterViewState extends State<PsSetCenterView> {
  PowerStationController _powerStationController =
      Get.put(PowerStationController());

  /// 货币类型
  List<String> _moneyTypeList = [];
  int _moneyTypeIndex = 0;

  /// 电价
  double _powerPrice = 0;

  @override
  void initState() {
    super.initState();

    // 电价列表（固定）
    _moneyTypeList = _powerStationController.getMoneyTypeList();

    loadData();
    _powerStationController.powerStationSetInfo.listen((p0) {
      loadData();
      if (this.mounted) setState(() {});
    });
  }

  loadData() {
    /// 货币类型
    String moneyType =
        '${_powerStationController.powerStationSetInfo['moneyType']}';
    _moneyTypeIndex = _moneyTypeList.indexOf(moneyType);

    /// 电价
    _powerPrice = _powerStationController.powerStationSetInfo['powerPrice'];
  }

  @override
  Widget build(BuildContext context) {
    return centerView();
  }

  centerView() {
    return Container(
      child: Column(
        children: [
          PowerStationSetItem(
            title: '${LangOf(context)?.power_setting?.electricity}（/kWh）',
            leftImgPath: 'imgs/set/set_electrovalence.png',
            rightView: Container(
                margin: EdgeInsets.only(right: 10.w),
                child: SilTextField(
                    showClearBtn: false,
                    textAlign: TextAlign.end,
                    height: 20.w,
                    text: '$_powerPrice',
                    hintText: LangOf(context)?.power_setting?.ele_prece,
                    textStyle: TextStyle(
                        fontSize: 14.sp, color: ColorUtils.color_font_minor),
                    onValid: (valid, value) {
                      if (value.isNum == false) {
                        String? msg =
                            LangOf(context)?.common?.electricity_noZero;
                        SilToast.show(msg ?? "");
                        return;
                      }
                      double price = double.parse(value);

                      /// 设置电价
                      _powerPrice = price;
                      _powerStationController.powerStationSetInfo
                          .update('powerPrice', (value) => _powerPrice);
                    },
                    interface: SilFormattersNumber())),
          ),
          PowerStationSetItem(
            title: LangOf(context)?.power_setting?.currency,
            leftImgPath: 'imgs/set/set_work_pattern.png',
            subTitle: _moneyTypeList[_moneyTypeIndex],
            tapRightViewFunc: showMoneyTypePop,
          ),
        ],
      ),
    );
  }

  /// 显示货币类型
  showMoneyTypePop() {
    SilBottomSheet.show(
        context: context,
        child: BottomSheetView(
            initialSelectedItem: _moneyTypeIndex,
            titles: _moneyTypeList,
            tapSureSeletedFunc: (selected) {
              /// 设置货币类型
              _moneyTypeIndex = selected;
              _powerStationController.powerStationSetInfo.update(
                  'moneyType', (value) => _moneyTypeList[_moneyTypeIndex]);
            }));
  }
}

/**
 * 密码数字
 */
class SilFormattersNumber implements SilFormattersInterface {
  @override
  List<TextInputFormatter> inputFormatters(int? min, int? max) {
    return [
      FilteringTextInputFormatter.allow(RegExp('[A-Za-z0-9.]')),
    ];
  }

  @override
  bool checkValid(String value, int? min, int? max) {
    bool valid = false;

    if (!SilUtilsTools.stringIsEmpty(value)) {
      valid = true;
    }

    return valid;
  }

  @override
  TextInputType type = TextInputType.numberWithOptions(decimal: true);
}
